package com.yunshipei.enterplorer.browser;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import com.yunshipei.utils.FileUtils;

import org.xwalk.core.XWalkNavigationHistory;
import org.xwalk.core.XWalkView;

public class HomeWebViewClient extends BaseHomeWebViewClient {

    private String mLocation;
    private String mHomeUrl;
    private HomeWebViewCallback mHomeWebViewCallback;

    public HomeWebViewClient(Context context, String homeUrl, XWalkView xWalkView, HomeWebViewCallback homeWebViewCallback) {
        super(context, xWalkView);
        mHomeUrl = homeUrl;
        mHomeWebViewCallback = homeWebViewCallback;
    }

    @Override
    public boolean shouldOverrideUrlLoading(XWalkView view, String url) {
        String temp = Uri.decode(url);
        if (temp.equals(mHomeUrl)) {
            view.loadUrl(url);
            return false;
        } else {
            mHomeWebViewCallback.handleAppUrl(url);
            return true;
        }
    }

    @Override
    public void onLoadFinished(XWalkView view, String url) {
        super.onLoadFinished(view, url);
        if (url.equals("about:blank") && view.getNavigationHistory().canGoBack()) {
            view.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);
        }
        XWalkNavigationHistory xWalkNavigationHistory = view.getNavigationHistory();
        if (xWalkNavigationHistory != null) {
            xWalkNavigationHistory.clear();
        }
        if (!TextUtils.isEmpty(mLocation)) {
            view.load("javascript:setLocation(\"" + mLocation + "\")", null);
        }
        String data = FileUtils.readAssertResource(view.getContext(), "_home.js");
        view.load("javascript:" + data, null);
    }

    public void setLocation(String location) {
        this.mLocation = location;
    }

    public interface HomeWebViewCallback {
        void handleAppUrl(String url);
    }
}
